<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>
            <el-badge v-if="limit > 0" :value="limit">
              <el-dropdown class="more">
                <el-button type="success" icon="Plus">
                  {{ i18n('common.create') }}
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="router.push({ name: 'kernel_user_form' })">
                      手动添加
                    </el-dropdown-item>

                    <el-dropdown-item @click="dialogVisible = true;loadQrcodeUrl()">
                      扫码添加
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-badge>
          </div>
          <div>
            <el-button type="primary" icon="Promotion" @click="router.push({ name: 'kernel_user_apply_list' })">
              {{ i18n('user.apply_info') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="general-situation">
        <div>
          <el-tag class="float-right p10 mr10" type="info" size="small" effect="dark" round>
            {{ totalPage }}
          </el-tag>
          <h5 class="float-right mr10">全部用户</h5>
        </div>
      </div>

      <div class="admin_main_block_select color" style="padding: 0 20px;">
        <el-form label-position="right" label-width="auto">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :label="i18n('user.nickname')">
                <el-input v-model="dataForm.nickname" :placeholder="i18n('common.please_input') + i18n('user.nickname')" clearable @change="getDataList(model)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :label="i18n('user.role_id')">
                <el-radio-group v-model="dataForm.role_id" @change="getDataList(model)">
                  <el-radio label="">{{ i18n('common.all') }}</el-radio>
                  <el-radio v-for="(v, k) in roleList" :key="k" :label="v.value">
                    {{ v.text }}
                    <span class="red">({{ v.total }})</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="4">
              <el-form-item :label="i18n('user.position')">
                <el-select
                  v-model="dataForm.detail__position"
                  :placeholder="i18n('common.please_select') + i18n('user.position')" clearable @change="getDataList(model)">
                  <el-option v-for="(v, k) in positionList" :label="v.text" :key="k" :value="v.value">
                    <span class="float-left">{{ v.text }}</span>
                    <span class="float-right">{{ v.total }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item :label="i18n('common.status')">
                <el-radio-group v-model="dataForm.status" @change="getDataList(model)">
                  <el-radio label="">{{ i18n('common.all') }}</el-radio>
                  <el-radio v-for="(v, k) in statusList" :key="k" :label="v.value">
                    {{ v.text }}
                    <span class="red">({{ v.total }})</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="admin_table_main">
        <el-table :data="dataList" v-loading="dataListLoading" @selection-change="selectionChangeHandle" stripe>
          <el-table-column type="selection" header-align="center" align="center">
          </el-table-column>

          <el-table-column prop="id" :label="i18n('common.id')" width="70">
          </el-table-column>

          <el-table-column :label="i18n('user.user_role_name')" width="100">
            <template v-slot="scope">
              <span v-if="scope.row.role">
                {{ scope.row.role.title }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="nickname" :label="i18n('user.nickname')">
            <template v-slot="scope">
              <dl class="table_dl">
                <dt>
                  <el-avatar :size="45" :src="scope.row.avatar">
                    <img src="@/assets/images/default/circle.png" />
                  </el-avatar>
                </dt>
                <dd class="table_dl_dd_all_30">
                  {{ i18n('user.nickname') }}： {{ scope.row.nickname }}
                </dd>
                <dd class="table_dl_dd_all_16_gray">
                  {{ i18n('user.create_time') }}： {{ scope.row.create_time }}
                </dd>
              </dl>
            </template>
          </el-table-column>

          <el-table-column prop="username" :label="i18n('user.username')" width="120">
          </el-table-column>

          <el-table-column prop="sex" :label="i18n('user.sex')" width="120">
            <template v-slot="scope">
              {{ scope.row.sex.text }}
            </template>
          </el-table-column>

          <el-table-column :label="i18n('user.position')" width="120">
            <template v-slot="scope">
              <span v-if="scope.row.detail">
                {{ scope.row.detail.position }}
              </span>
            </template>
          </el-table-column>

          <el-table-column :label="i18n('user.is_bind')" width="100">
            <template v-slot="scope">
              {{ scope.row.is_bind.text }}
            </template>
          </el-table-column>

          <el-table-column :label="$t('common.status')" width="80">
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.status.value"
                active-value="1"
                inactive-value="2"
                size="large"
                inline-prompt
                :active-text="$t('common.enable')"
                :inactive-text="$t('common.disable')"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="handleStatus($event, scope.row.id, 'status')">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column prop="last_login_time" :label="i18n('user.last_login_time')" width="160">
          </el-table-column>

          <el-table-column :label="i18n('common.handle')" fixed="right" width="290">
            <template v-slot="scope">
              <el-button type="primary" icon="Edit" @click="router.push({ name: 'kernel_user_form', query: { id: scope.row.id } })">
                {{ i18n('common.update') }}
              </el-button>

              <el-button v-if="1 != scope.row.id" type="danger" icon="Delete" @click="deleteHandle(scope.row.id)">
                {{ i18n('common.delete') }}
              </el-button>

              <el-dropdown class="more">
                <el-button icon="More">
                  {{ i18n('common.more') }}
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="initializationHandle(scope.row.id)">
                      {{ i18n('common.initialization_password') }}
                    </el-dropdown-item>

                    <el-dropdown-item v-if="scope.row.role_id != 1" @click="router.push({ name: 'kernel_user_role', query: { id: scope.row.id } })">
                      {{ i18n('user.permission') }}
                    </el-dropdown-item>

                    <el-dropdown-item @click="router.push({ name: 'kernel_user_bind_form', query: { id: scope.row.id } })">
                      {{ i18n('user.bind.info') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="admin_table_main_pagination">
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :page-size="pageSize"
            :total="totalPage"
            :current-page="pageIndex"
            background
            layout="prev, pager, next, jumper, total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="用户扫码注册" width="500" center>
      <div class="text-center mt20">
        <el-image class="qrcode" :src="qrcode_url"/>
      </div>
      <template #footer>
        <div class="dialog-footer mb20">
          <el-button @click="copyToClipboard">复制二维码</el-button>
          <el-button type="primary" @click="downloadQrcode">
            下载二维码
          </el-button>
        </div>

        <div class="alert">
          <div class="title">
            将二维码发给客户微信，扫码即可完成注册！
          </div>
          <div class="content">
            二维码有效期为24小时，过期后需要重新获取
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="user-list">
  import { useBase } from "@/hooks/base/useBase"
  import { useTable } from "@/hooks/table/useTable"

  const { router, i18n, isAuth } = useBase()

  const model = ref('user')

  const refresh = inject("refresh")
  const limit = ref(0)
  const roleList = ref([])
  const positionList = ref([])
  const statusList = ref([])

  const dialogVisible = ref(false)
  const qrcode_url = ref('')

  const dataForm = reactive([
    'nickname',
    'mobile',
    'role_id',
    'detail__position',
    'status',
    'last_login_time'
  ])

  const {
    dataList,
    pageIndex,
    pageSize,
    totalPage,
    handleStatus,
    dataListLoading,
    sizeChangeHandle,
    currentChangeHandle,
    selectionChangeHandle,
    getDataList,
    deleteHandle,
  } = useTable(model.value, dataForm)

  const initializationHandle = (id) => {
    let message = '您确定要初始化当前用户的登录密码？'

    $messagebox.confirm(message, i18n('common.prompt'), {
      confirmButtonText: i18n('common.confirm'),
      cancelButtonText: i18n('common.cancel'),
      type: 'warning'
    }).then(() => {
      $http({
        url: $http.adornUrl('/' + model.value + '/password'),
        method: 'post',
        data: {id: id}
      }).then(({data}) => {
        if (data && data.status === 200) {
          $message.success(i18n('common.handle_success'));
          refresh();
        } else {
          $message.error(data.message)
        }
      })
    }).catch(() => {})
  }

  const loadUserLimit = () => {
    $http({
      url: $http.adornUrl('/organization/limit'),
      method: 'get',
    }).then(({ data }) => {
      if (data && data.status === 200) {
        limit.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }


  const loadSearchList = () => {
    $http({
      url: $http.adornUrl('/user/search/data'),
      method: 'get',
      params: $http.adornParams({}),
    }).then(({data}) => {
      if (data && data.status === 200) {
        roleList.value = data.data.role
        positionList.value = data.data.position
        statusList.value = data.data.status
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadQrcodeUrl = () => {
    $http({
      url: $http.adornUrl('/business/qrcode/mini/data'),
      method: 'get',
      params: $http.adornParams({
        path: '/pages-personal/addAccount/addAdmin',
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        qrcode_url.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const copyToClipboard = () => {
    navigator.clipboard.writeText(qrcode_url.value);
    dialogVisible.value = false
  }

  const downloadQrcode = () => {
    if(qrcode_url.value) {
      window.open(qrcode_url.value)
    }
  }

  onMounted(() => {
    getDataList(model)

    loadUserLimit()
    loadSearchList()
  })
</script>


<style scoped lang="scss">
  .more {
    margin: 0px;
  }
  .qrcode {
    width: 10vw;
    height: 10vw;
  }
  .alert {
    text-align: left;
    padding: 10px 5vw;
    color: var(--el-color-warning);
    background-color: var(--el-color-warning-light-9);

    .title {
      font-size: 13px;
      font-weight: bold;
    }
    .content {
      font-size: 12px;
      margin-top: 5px;
    }
  }
</style>
